#!/bin/bash
# elasticsearch 快捷docker安装运行
# 创建目录并移动脚本的函数
function dockerCreateStart() {
  name="$1"
  version="$2"
  asName="$3"
  portMap=$4
  volumesMap=$5
  dockerMap=$6
  copyDockerMap=$7
  lastDockerMap=$8
  #MYSQL_ROOT_PASSWORD=$9

  # 拉取 Docker 镜像（取消注释以启用）
  docker pull "${name}:${version}"

  # 删除同名容器
  docker rm -f "${asName}" &>/dev/null

  dockerRun="docker run "
  dockerRunTemp="docker run "

  if [ "${#portMap[@]}" -eq 0 ]; then
    echo ""
  else
    # 添加端口映射参数
    for element in "${portMap[@]}"; do
      dockerRun+="-p $element "
      dockerRunTemp+="-p $element "
    done
  fi

  if [ "${#dockerMap[@]}" -eq 0 ]; then
    echo ""
  else
    # 添加其他 Docker 参数
    for element in "${dockerMap[@]}"; do
      dockerRun+="$element "
      dockerRunTemp+="$element "
    done
  fi

  if [ "${#volumesMap[@]}" -eq 0 ]; then
    echo ""
  else
    # 添加卷映射参数
    for element in "${volumesMap[@]}"; do
      dockerRun+="-v $element "
    done
  fi

  dockerRun+="${name}:${version} "
  dockerRunTemp+="${name}:${version} "

  # 添加镜像及额外参数
  if [ "${#lastDockerMap[@]}" -eq 0 ]; then
    echo ""
  else
    for element in "${lastDockerMap[@]}"; do
      dockerRun+=" $element "
      dockerRunTemp+=" $element "
    done
  fi

  echo "$dockerRunTemp"
  eval "$dockerRunTemp"

  if [ "${#copyDockerMap[@]}" -eq 0 ]; then
    echo ""
  else
    echo "复制 开始"
    # 复制 Docker 映射文件
    for element in "${copyDockerMap[@]}"; do
      echo "复制 $element"
      IFS=':' read -r source dest <<<"$element"
      echo "docker cp ${asName}:${source} ${dest}"
      docker cp "${asName}":"${source}" "${dest}"
    done

    echo "复制 完成"
  fi

  # 删除同名容器
  docker rm -f "${asName}" &>/dev/null

  echo "正式启动挂载"
  echo "$dockerRun"
  eval "$dockerRun"
  #$dockerRun

  read -r -p "查看 $name 运行日志?【Y/N】" input
  if [[ "${input,,}" =~ ^(yes|y)$ ]]; then
      docker logs -f -t --tail=200 ${asName}
  else
      echo ""
  fi
}

function demo() {
  # 拉取Zookeeper镜像
  docker pull wurstmeister/zookeeper

  # 启动Zookeeper容器
  docker run --name zookeeper -p 2181:2181 --restart always -d wurstmeister/zookeeper
  docker run --name zookeeper -p 2181:2181 -d wurstmeister/zookeeper

  # 拉取Kafka镜像
  docker pull wurstmeister/kafka

  # 启动Kafka容器，连接到Zookeeper
  docker run --name kafka -p 9092:9092 --restart always \
    -e KAFKA_BROKER_ID=0 \
    -e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \
    -e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT \
    -e KAFKA_LISTENERS=INSIDE://:9092,OUTSIDE://:9094 \
    -e KAFKA_ADVERTISED_LISTENERS=INSIDE://kafka:9092,OUTSIDE://localhost:9094 \
    -e KAFKA_INTER_BROKER_LISTENER_NAME=INSIDE \
    -d wurstmeister/kafka
}

# 创建目录并移动脚本的函数
function createStart() {
  local dockerVolumes="$1"
  local name="$2"
  local port="$3"
  local scriptName="${name}.sh"
  local destination="/${dockerVolumes}/${name}/${port}"
  rm -rf "${destination}"
  # 为脚本添加执行权限
  chmod +x "${scriptName}"

  # 使用 mkdir -p 创建父目录（如果不存在）
  mkdir -p "${destination}"

  # 删除已存在的脚本文件
  [ -f "/${dockerVolumes}/${name}/${scriptName}" ] && rm -rf "/${dockerVolumes}/${name}/${scriptName}"

  # 在移动之前检查脚本文件是否存在
  if [ -f "${scriptName}" ]; then
    cp "${scriptName}" "/${dockerVolumes}/${name}/"
    echo "脚本 '${scriptName}' 已复制到 '/${dockerVolumes}/${name}/'"
  else
    echo "错误：当前目录中找不到脚本 '${scriptName}'"
      read -r -p "继续 运行脚本?【Y/N】" input
      if [[ "${input,,}" =~ ^(yes|y)$ ]]; then
          echo "继续执行"
      else
          exit 1
      fi
  fi
}

function zookeeper() {
  # docker run -p 2181:2181 -v /etc/localtime:/etc/localtime --network=common-network -d --name zookeeper zookeeper
  # 默认值
  networkName=$1
  dockerVolumes=$2
  #镜像名
  name=$3
  #别名
  asName=$4
  #版本
  version=$5
  port=$6
  #将容器  端口映射到宿主机的  端口
  portMap=("$port:2181")
  #挂载地址
  v0="/etc/localtime:/etc/localtime"
  v1="/$dockerVolumes/$asName/$port/$asName/conf:/opt/${asName}-3.4.13/conf"
  v2="/$dockerVolumes/$asName/$port/$asName/data:/opt/${asName}-3.4.13/data"
  #v3="/$dockerVolumes/$name/logs:/usr/share/elasticsearch/logs"

  volumesMap=("$v0" "$v1" "$v2")

  #环境配置
  dockerMap=("-d" "--name=${asName}" "--network=${networkName}")
  #dockerMap+=("--restart=always")
  cp1="/opt/${asName}-3.4.13:/$dockerVolumes/$name/$port/$asName"
  copyDockerMap=(cp1)
  lastDockerMap=()
  echo "${zookeeperAsName} 初始化 启动 挂载..."
  createStart $dockerVolumes $asName $port
  dockerCreateStart "${name}" "${version}" "${asName}" $portMap $volumesMap $dockerMap $copyDockerMap $lastDockerMap

  echo "============================================="
  echo "============================================="
  for element in "${volumesMap[@]}"; do
    echo "        ${asName} Docker 挂载目录：            "
    echo ${element}
  done
  echo "============================================="
}

function kafka() {
  # 默认值
  networkName=$1
  dockerVolumes=$4
  #镜像名
  name=$5
  #别名
  asName=$2
  #版本
  version="latest"
  port=$3
  #将容器  端口映射到宿主机的  端口
  portMap=("$port:2181")
  #挂载地址
  v0="/etc/localtime:/etc/localtime"
  v1="/$dockerVolumes/$asName/$port/${asName}-3.4.13//conf:/opt/${asName}-3.4.13/conf"
  v2="/$dockerVolumes/$asName/$port/${asName}-3.4.13//data:/opt/${asName}-3.4.13/data"
  #v3="/$dockerVolumes/$name/logs:/usr/share/elasticsearch/logs"

  volumesMap=("$v0" "$v1" "$v2")

  #环境配置
  dockerMap=("-d" "--name=${asName}" "--network=${networkName}")
  #dockerMap+=("--restart=always")
  cp1="/opt/${asName}-3.4.13:/$dockerVolumes/$name/$port/"
  copyDockerMap=(cp1)
  lastDockerMap=()

  dockerCreateStart "${name}" "${version}" "${asName}" $portMap $volumesMap $dockerMap $copyDockerMap $lastDockerMap
}
function main() {

  # 默认值
  networkName="common-network"
  dockerVolumes="docker-volumes"
  #镜像名
  zookeeperName="wurstmeister/zookeeper"
  kafkaName="wurstmeister/kafka"
  #别名
  zookeeperAsName="zookeeper"
  kafkaAsName="kafka"
  #版本
  zookeeperVersion="latest"
  zookeeperPortHost="2181"
  kafkaVersion="latest"
  kafkaPortHost="2181"
  docker network create $networkName
  zookeeper $networkName $dockerVolumes $zookeeperName $zookeeperAsName $zookeeperVersion $zookeeperPortHost
}

main
